package com.itlin.exception;

import com.itlin.common.CustomException;
import com.itlin.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author 所谓伊人
 * @date 2022/3/21 - 15:11
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获插入重复数据异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handerSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {

        e.printStackTrace();

        String message = e.getMessage();

        if (message.contains("Duplicate entry")) {
            return R.error(message.split(" ")[2]+"已存在");
        }else {
            return R.error("未知错误");
        }
    }

    /**
     * 异常处理方法之删除是外键的分类
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        ex.printStackTrace();
        return R.error(ex.getMessage());
    }
}
